
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- to是跳转的路径,点击就会跳转 -->
      <el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <el-input class="search" v-model="query" placeholder="请输入要搜索的内容">
      <el-button slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <!-- 添加按钮 -->
    <el-button style="margin-left:-5px;" type="success" plain @click="dialogVisibleadd=true">添加</el-button>
    <!-- 用户列表 -->
    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="120"></el-table-column>
      <el-table-column prop="role_name" label="角色" width="120"></el-table-column>

      <el-table-column label="用户状态" width="100">
        <!-- 使用插槽添加状态 -->
        <template slot-scope="scope">
          <!-- scope.row 就拿到当前遍历的那一行数据 -->
          <el-switch
            @change="changeState(scope.row.mg_state,scope.row.id)"
            v-model="scope.row.mg_state"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit" plain type="primary" @click="editUser(scope.row.id)"></el-button>
          <el-button size="mini" icon="el-icon-delete" plain type="danger" @click="deleteUser(scope.row.id)"></el-button>
          <el-button size="mini" icon="el-icon-check" plain type="warning"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 新增用户的对话框,默认是隐藏的 -->
    <el-dialog title="新增用户" :visible.sync="dialogVisibleadd" width="50%">
      <el-form :model="addUserObj" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserObj.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserObj.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleadd = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="dialogVisibleaEdit" width="50%">
      <el-form :model="editUserObj" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserObj.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleaEdit = false">取 消</el-button>
        <el-button type="primary" @click="editUser2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      query: "",
      pagenum: 1, //页面
      pagesize: 5, //每页显示的条数
      userList: [], //用户列表
      total: 0 ,//总条数
      dialogVisibleadd:false,
      dialogVisibleaEdit:false,
      addUserObj: {//新增用户的数据
          username: '',
          password: '',
          email: '',
          mobile: ''
      },
      editUserObj:{},

      rules:{
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
        password: [
            { required: true, message: '请输入密码', trigger: 'change' }
          ],
      }
    };
  },
  created() {
    //users组件实例创建完成之后会自动执行的函数
    this.getUserListData();
  },
  methods: {
    //方法
    // 发送请求,获取用户数据
    getUserListData() {
      this.$axios
        .get("users", {
          params: {
            pagenum: this.pagenum,
            pagesize: this.pagesize,
            query: this.query
          }
        })
        .then(res => {
          this.userList = res.data.data.users;
          // console.log(this.userList);
          // 获取数据中的条数
          this.total = res.data.data.total;
        });
    },
    // 当页面改变时触发
    handleSizeChange(pagesize) {
      this.pagesize = pagesize;
      this.getUserListData();
    },
    // 当前页面发生改变的时候触发
    handleCurrentChange(pagenum) {
      this.pagenum = pagenum;
      this.getUserListData();
    },
    // 更改用户的状态
    changeState(state,userId) {
      // 发送请求
      this.$axios.put(`users/${userId}/state/${state}`).then(res=>{
        console.log(res)
        if(res.data.meta.status==200){//创建成功
          this.$message({
            message: res.data.meta.msg,
            type: 'success'
          })
        }
      })
    },
    //新增用户
    addUser() {
      // 拿到form表单
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$axios.post(`users`,this.addUserObj).then(res=>{
              // console.log(res)
              if(res.data.meta.status==201){//创建成功
                //隐藏弹框
                this.dialogVisibleadd = false
                //提示
                this.$message({
                message: res.data.meta.msg,
                type: 'success'
              })
              //重新查询列表
              this.getUserListData();
              }
            })
          }
        });
      },
    //修改用户,查询用户信息,弹出窗口,把用户的信息显示在弹出窗口的form表单上
    editUser(userId){
      //发送请求从后台获取数据
      this.$axios.get(`users/${userId}`).then(res=>{
        // console.log(res)
        // 把返回回来的数据赋值给editUserObj,通过editUserObj.xxx显示到表单中
        this.editUserObj = res.data.data

        //弹出对话框
        this.dialogVisibleaEdit = true
      })
    },
    //修改用户提交,弹出修改的结果,重新获取页面的信息
    editUser2(){
      this.$axios.put(`users/${this.editUserObj.id}`,this.editUserObj).then(res=>{
        // console.log(res)
        if(res.data.meta.status ===200){
          this.$message ({
            message: res.data.meta.msg,
            type: 'success'
          })
          //关闭对话框
          this.dialogVisibleaEdit = false
          //刷新列表
          this.getUserListData()
        }
      })
    },
    //删除用户
    deleteUser(userId){
      // 先弹出窗口确认是否删除
       this.$confirm('确定删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {//确认后执行的删除逻辑
          this.$axios.delete(`users/${userId}`).then(res=>{
            // console.log(res)
            if(res.data.meta.status ===200){
              this.$message ({
                message: res.data.meta.msg,
                type: 'success'
              })
              //数据库删除完之后就需要重新获取数据
              // 重置为第一页
              this.pagenum = 1
              // 重新渲染页面

              this.getUserListData();
            }
          })
          
        }).catch(() => {//删除失败的
                   
        });
    }
  },
    
};
</script>

<style scope>
.el-breadcrumb {
  background-color: #d3dce6;
  height: 50px;
  line-height: 50px;
  padding-left: 10px;
}
.el-pagination {
  background-color: #d3dce6;
  padding-top: 10px;
  height: 35px;
  line-height: 35px;
}
.search {
  width: 300px;
}
</style>

